package com.jrx.anytxn.reporting.job.lsFile.config;

import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.job.lsFile.step.*;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 生成还款计划文件(按照更新时间 增量抽取)
 *
 * @author liuyang
 * @date 2021-03-13
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class GenerateLSRepaymentFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateLSRepaymentFileConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Autowired
    private LSRepaymentFileListener repaymentFileListener;
    @Autowired
    private LSRepaymentFileProcessor repaymentFileProcessor;
    @Autowired
    private LSRepaymentFileWriter repaymentFileWriter;

    @Bean
    public Job generateLSRepaymentFileJob() {
        return jobBuilderFactory.get("generateLSRepaymentFileJob").incrementer(new RunIdIncrementer()).listener(repaymentFileListener)
                .start(generateNormalLSRepaymentFileStep())
                .next(generatePayoffLSRepaymentFileStep())
                .build();
    }

    @Bean
    public Step generateNormalLSRepaymentFileStep() {
        return stepBuilderFactory.get("generateNormalLSRepaymentFileStep")
                .<Long, String>chunk(anyTxnBatchProperties.getFileConfig().getChunkLimit())
                .reader(repaymentNormalLSFileReader())
                .processor(repaymentFileProcessor)
                .writer(repaymentFileWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getFileConfig().getThrottleLimit())
                .build();
    }

    @Bean
    public Step generatePayoffLSRepaymentFileStep() {
        return stepBuilderFactory.get("generatePayoffLSRepaymentFileStep")
                .<Long, String>chunk(anyTxnBatchProperties.getFileConfig().getChunkLimit())
                .reader(repaymentPayoffLSFileReader())
                .processor(repaymentFileProcessor)
                .writer(repaymentFileWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getFileConfig().getThrottleLimit())
                .build();
    }

    @Bean
    @StepScope
    public ItemReader<Long> repaymentNormalLSFileReader() {
        logger.info("生成临商还款计划文件批量启动,读取正常的还款计划，机构：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        BtBatchStatus batchStatus = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2, ReportingConstant.CUTOVER_END,
                org.getTenantId(), org.getToday());
        Date startTime = null;
        if (null != batchStatus) {
            startTime = batchStatus.getCreateTime();
        }
        return new LSNormalRepaymentFileReader(sqlSessionFactory, anyTxnBatchProperties.getFileConfig().getPageSize(), startTime);
    }

    @Bean
    @StepScope
    public ItemReader<Long> repaymentPayoffLSFileReader() {
        logger.info("生成临商还款计划文件批量启动,读取第一次结清的还款计划，机构：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        BtBatchStatus batchStatus = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2, ReportingConstant.CUTOVER_END,
                org.getTenantId(), org.getToday());
        Date startTime = null;
        if (null != batchStatus) {
            startTime = batchStatus.getCreateTime();
        }
        Date payoffDate = org.getToday();
        return new LSPayoffRepaymentFileReader(sqlSessionFactory, anyTxnBatchProperties.getFileConfig().getPageSize(), payoffDate, startTime);
    }
}
